﻿using System;
using System.Collections.Generic;
using System.Linq;
using Simple.Data;
using Model.User;

namespace Model.Communication
{
    public class Topic
    {
        protected DateTime created;
        protected String subject;
        protected Int32 id;
        protected Int32 forumId;
        protected Int32 authorId;

        protected Topic()
        {
        }

        protected Topic(int id, String subject, DateTime created, int forum, int author)
        {
            this.id = id;
            this.subject = subject;
            this.created = created;
            this.forumId = forum;
            this.authorId = author;
        }

        public static Topic create(Forum forum, Person author, String subject, DateTime created)
        {
            var topic = Database.Open().Topic.Insert(Subject: subject, Created: created, 
                                                     Forum: forum.getId(), Author: author.getId());

            if (topic == null)
                return null;

            return new Topic(topic.id, subject, created, topic.forum, topic.author);
        }

        public static int getCount(Forum forum)
        {
            return Database.Open().Topic.GetCountByForum(forum.getId());
        }

        public static Topic[] get(Forum forum, int amount, int skip)
        {
            var topicsRows = Database.Open().Topic.FindAllByForum(forum.getId()).
                                                                    Skip(skip).Take(amount);

            List<Topic> topics = new List<Topic>();

            foreach (var p in topicsRows)
            {
                topics.Add(new Topic(p.id, p.subject, p.created, p.forum, p.author));
            }

            return topics.ToArray();
        }

        public static Topic[] getAll(Forum forum)
        {
            int count = getCount(forum);
            return get(forum, count, 0);
        }

        public int getId()
        {
            return id;
        }

        public int getAuthorId()
        {
            return authorId;
        }

        public int getForumId()
        {
            return forumId;
        }

        public DateTime getCreated()
        {
            return created;
        }

        public String getSubject()
        {
            return subject;
        }
    }
}